/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.shoplink.launcher;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Instrumentation;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.net.NetworkInfo.DetailedState;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.AuthAlgorithm;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WifiEnterpriseConfig;
import android.net.wifi.WifiEnterpriseConfig.Eap;
import android.net.wifi.WifiEnterpriseConfig.Phase2;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.security.Credentials;
import android.security.KeyStore;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.format.Formatter;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sholink.wheel.adapters.AbstractWheelTextAdapter;
import com.shoplink.view.MyToast;
import com.shoplink.view.SoftkeyboardListenEditText;
import com.shoplink.view.SoftkeyboardListenEditText.DoKeyBackListener;
import com.tcl.shoplink.wheel.WheelSpinnerView;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class WifiDialog extends AlertDialog implements View.OnClickListener,
		TextWatcher, AdapterView.OnItemSelectedListener, View.OnKeyListener {
	private static final String KEYSTORE_SPACE = "keystore://";

	static final int BUTTON_SUBMIT = DialogInterface.BUTTON_POSITIVE;
	static final int BUTTON_FORGET = DialogInterface.BUTTON_NEUTRAL;

	final boolean edit;
	private final View.OnClickListener mListener;
	private final AccessPoint mAccessPoint;

	private View mView;
	private TextView mSsid;
	private int mSecurity;
	private String[] type;
	private SoftkeyboardListenEditText mPassword, newPasswod;

	private WheelSpinnerView mEapMethod;
	private WheelSpinnerView mEapCaCert;
	private WheelSpinnerView mPhase2;
	private WheelSpinnerView mEapUserCert;
	private TextView mEapIdentity;
	private TextView mEapAnonymous;
	private TextView titleView;
	private ImageView titleIcon;
	private Button mButtonPositive, mButtonNegative, mButtonNeutral;
	private Message mButtonPositiveMessage;
	private Message mButtonNegativeMessage;
	private Message mButtonNeutralMessage;
	private WheelSpinnerView security;
	/* These values come from "wifi_peap_phase2_entries" resource array */
	public static final int WIFI_PEAP_PHASE2_NONE = 0;
	public static final int WIFI_PEAP_PHASE2_MSCHAPV2 = 1;
	public static final int WIFI_PEAP_PHASE2_GTC = 2;
	private String unspecifiedCert = "unspecified";
	private CheckBox mCheckBox;
	private LinearLayout parentLayout1, parentLayout2;
	private boolean isAddnet;
	// static boolean requireKeyStore(WifiConfiguration config) {
	// String values[] = { config.ca_cert.value(), config.client_cert.value() };
	// for (String value : values) {
	// if (value != null && value.startsWith(KEYSTORE_SPACE)) {
	// return true;
	// }
	// }
	// return false;
	// }

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			simulateKey(KeyEvent.KEYCODE_DPAD_DOWN);
		};
	};

	public WifiDialog(Context context, View.OnClickListener listener,
			AccessPoint accessPoint, boolean edit) {
		super(context, R.style.apDialog);
		this.edit = edit;
		mListener = listener;
		mAccessPoint = accessPoint;
		mSecurity = (accessPoint == null) ? AccessPoint.SECURITY_NONE
				: accessPoint.security;
		unspecifiedCert = context.getString(R.string.wifi_unspecified);
	}

	@SuppressLint("NewApi")
	public WifiConfiguration getConfig() {
		if (mAccessPoint != null && mAccessPoint.networkId != -1 && !edit) {
			return null;
		}

		WifiConfiguration config = new WifiConfiguration();

		if (mAccessPoint == null) {
			config.SSID = AccessPoint.convertToQuotedString(mSsid.getText()
					.toString());
			// If the user adds a network manually, assume that it is hidden.
			config.hiddenSSID = true;
		} else if (mAccessPoint.networkId == -1) {
			config.SSID = AccessPoint.convertToQuotedString(mAccessPoint.ssid);
		} else {
			config.networkId = mAccessPoint.networkId;
		}

		switch (mSecurity) {
		case AccessPoint.SECURITY_NONE:
			config.allowedKeyManagement.set(KeyMgmt.NONE);
			return config;

		case AccessPoint.SECURITY_WEP:
			config.allowedKeyManagement.set(KeyMgmt.NONE);
			config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
			config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
			if (mPassword != null && mPassword.length() != 0) {
				int length = mPassword.length();
				String password = mPassword.getText().toString();
				// WEP-40, WEP-104, and 256-bit WEP (WEP-232?)
				if ((length == 10 || length == 26 || length == 58)
						&& password.matches("[0-9A-Fa-f]*")) {
					config.wepKeys[0] = password;
				} else {
					config.wepKeys[0] = '"' + password + '"';
				}
			} else if (newPasswod != null && newPasswod.length() != 0) {
				int length = newPasswod.length();
				String password = newPasswod.getText().toString();
				// WEP-40, WEP-104, and 256-bit WEP (WEP-232?)
				if ((length == 10 || length == 26 || length == 58)
						&& password.matches("[0-9A-Fa-f]*")) {
					config.wepKeys[0] = password;
				} else {
					config.wepKeys[0] = '"' + password + '"';
				}
			}
			return config;

		case AccessPoint.SECURITY_PSK:
			config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
			if (mPassword != null && mPassword.length() != 0) {
				String password = mPassword.getText().toString();
				if (password.matches("[0-9A-Fa-f]{64}")) {
					config.preSharedKey = password;
				} else {
					config.preSharedKey = '"' + password + '"';
				}
			} else if (newPasswod != null && newPasswod.length() != 0) {
				String password = newPasswod.getText().toString();
				if (password.matches("[0-9A-Fa-f]{64}")) {
					config.preSharedKey = password;
				} else {
					config.preSharedKey = '"' + password + '"';
				}
			}
			return config;

		case AccessPoint.SECURITY_EAP:
			// config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
			// config.allowedKeyManagement.set(KeyMgmt.IEEE8021X);
			// config.eap.setValue((String) mEapMethod.getSelectedItem());
			//
			// config.phase2
			// .setValue((mPhase2.getSelectedItemPosition() == 0) ? ""
			// : "auth=" + mPhase2.getSelectedItem());
			// config.ca_cert
			// .setValue((mEapCaCert.getSelectedItemPosition() == 0) ? ""
			// : KEYSTORE_SPACE + Credentials.CA_CERTIFICATE
			// + (String) mEapCaCert.getSelectedItem());
			// config.client_cert
			// .setValue((mEapUserCert.getSelectedItemPosition() == 0) ? ""
			// : KEYSTORE_SPACE + Credentials.USER_CERTIFICATE
			// + (String) mEapUserCert.getSelectedItem());
			// config.private_key
			// .setValue((mEapUserCert.getSelectedItemPosition() == 0) ? ""
			// : KEYSTORE_SPACE + Credentials.USER_PRIVATE_KEY
			// + (String) mEapUserCert.getSelectedItem());
			// config.identity.setValue((mEapIdentity.length() == 0) ? ""
			// : mEapIdentity.getText().toString());
			// config.anonymous_identity
			// .setValue((mEapAnonymous.length() == 0) ? ""
			// : mEapAnonymous.getText().toString());
			// if (mPassword.length() != 0) {
			// config.password.setValue(mPassword.getText().toString());
			// }
			// return config;
			config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
			config.allowedKeyManagement.set(KeyMgmt.IEEE8021X);
			config.enterpriseConfig = new WifiEnterpriseConfig();
			int eapMethod = mEapMethod.getSelectedItemPosition();
			int phase2Method = mPhase2.getSelectedItemPosition();
			config.enterpriseConfig.setEapMethod(eapMethod);
			switch (eapMethod) {
			case Eap.PEAP:
				// PEAP supports limited phase2 values
				// Map the index from the PHASE2_PEAP_ADAPTER to the one used
				// by the API which has the full list of PEAP methods.
				switch (phase2Method) {
				case WIFI_PEAP_PHASE2_NONE:
					config.enterpriseConfig.setPhase2Method(Phase2.NONE);
					break;
				case WIFI_PEAP_PHASE2_MSCHAPV2:
					config.enterpriseConfig.setPhase2Method(Phase2.MSCHAPV2);
					break;
				case WIFI_PEAP_PHASE2_GTC:
					config.enterpriseConfig.setPhase2Method(Phase2.GTC);
					break;
				default:
					Log.e("cedar", "Unknown phase2 method" + phase2Method);
					break;
				}
				break;
			default:
				// The default index from PHASE2_FULL_ADAPTER maps to the API
				config.enterpriseConfig.setPhase2Method(phase2Method);
				break;
			}
			String caCert = (String) mEapCaCert.getSelectedItem();
			if (caCert.equals(unspecifiedCert))
				caCert = "";
			config.enterpriseConfig.setCaCertificateAlias(caCert);
			String clientCert = (String) mEapUserCert.getSelectedItem();
			if (clientCert.equals(unspecifiedCert))
				clientCert = "";
			config.enterpriseConfig.setClientCertificateAlias(clientCert);
			config.enterpriseConfig.setIdentity(mEapIdentity.getText()
					.toString());
			config.enterpriseConfig.setAnonymousIdentity(mEapAnonymous
					.getText().toString());
			if (mPassword != null) {
				if (mPassword.isShown()) {
					// For security reasons, a previous password is not
					// displayed to
					// user.
					// Update only if it has been changed.
					if (mPassword.length() > 0) {
						config.enterpriseConfig.setPassword(mPassword.getText()
								.toString());
					}
				} else {
					// clear password
					config.enterpriseConfig.setPassword(mPassword.getText()
							.toString());
				}
			} else if (newPasswod != null) {
				if (newPasswod != null && newPasswod.isShown()) {
					// For security reasons, a previous password is not
					// displayed to
					// user.
					// Update only if it has been changed.
					if (newPasswod.length() > 0) {
						config.enterpriseConfig.setPassword(newPasswod
								.getText().toString());
					}
				} else {
					// clear password
					config.enterpriseConfig.setPassword(newPasswod.getText()
							.toString());
				}
			}

			break;
		}
		return null;
	}

	@Override
	public void setTitle(CharSequence title) {
		if (titleView != null) {
			titleView.setText(title);
		}
	}

	class SecurityAdapter extends AbstractWheelTextAdapter {
		ArrayList<String> securityList;

		protected SecurityAdapter(Context context, String[] type) {
			super(context, R.layout.video_player_definition_item,
					R.id.definition_item);
			securityList = new ArrayList<String>(Arrays.asList(type));
		}

		@Override
		public int getItemsCount() {
			if (securityList != null) {
				return securityList.size();
			}
			return 0;
		}

		@Override
		protected CharSequence getItemText(int index) {
			// TODO Auto-generated method stub
			return securityList.get(index);
		}

		@Override
		public View getItem(int index, View convertView, ViewGroup parent) {
			View view = super.getItem(index, convertView, parent);
			return view;
		}

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// mView = getLayoutInflater().inflate(R.layout.wifi_dialog, null);
		// setView(mView);
		// setInverseBackgroundForced(true);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wifi_dialog_layout);
		getWindow()
				.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
		Context context = getContext();
		Resources resources = context.getResources();

		mView = findViewById(R.id.wifi_dialog_main);
		titleView = (TextView) findViewById(R.id.alertTitle);
		titleIcon = (ImageView) findViewById(R.id.alertTitleIcon);
		mButtonPositive = (Button) findViewById(R.id.button1);
		mButtonNegative = (Button) findViewById(R.id.button2);
		parentLayout1 = (LinearLayout) findViewById(R.id.dialog_1_layout);
		parentLayout2 = (LinearLayout) findViewById(R.id.dialog_2_layout);
		mButtonNegative.setOnKeyListener(new View.OnKeyListener() {

			@Override
			public boolean onKey(View arg0, int arg1, KeyEvent keyEvent) {
				if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT) {
					if (keyEvent.getAction() == KeyEvent.ACTION_UP
							|| (keyEvent.getAction() == KeyEvent.ACTION_DOWN && keyEvent
									.getRepeatCount() > 1)) {
						if (!mButtonPositive.isEnabled()) {
							// SoundManager.getInstance()
							// .playInvalidKeyPressSoundEffect();
						}
					}
				}
				return false;
			}
		});
		mButtonNeutral = (Button) findViewById(R.id.button3);
		setButton(DialogInterface.BUTTON_NEGATIVE,
				context.getString(R.string.wifi_cancel), mListener);
		if (mAccessPoint == null) {
			isAddnet = true;
			titleIcon.setVisibility(View.INVISIBLE);
			setTitle(R.string.wifi_add_network);
			mView.findViewById(R.id.type).setVisibility(View.VISIBLE);
			mSsid = (TextView) mView.findViewById(R.id.ssid);
			mSsid.addTextChangedListener(this);
			// ((Spinner) mView.findViewById(R.id.security))
			// .setOnItemSelectedListener(this);
			security = (WheelSpinnerView) mView.findViewById(R.id.security);
			type = resources.getStringArray(R.array.wifi_security);
			security.setAdapterData(type);
			security.setCyclic(true);
			View.OnKeyListener mSecurityKeyListener = new View.OnKeyListener() {
				@Override
				public boolean onKey(View v, int keyCode, KeyEvent event) {
					if (event.getAction() == KeyEvent.ACTION_DOWN) {
						if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
							int position = security.getCurrentItem() - 1;
							security.setCurrentItem(position);
							position = position < 0 ? type.length - 1
									: position;
							onSecurityChanged(position);
							return true;
						} else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
							int position = security.getCurrentItem() + 1;
							security.setCurrentItem(position);
							position = position > type.length - 1 ? 0
									: position;
							onSecurityChanged(position);
							return true;
						}
					}
					return false;
				}

			};
			// security.setOnKeyListener(mSecurityKeyListener);
			security.setOnKeyListener(this);
			setButton(BUTTON_SUBMIT, context.getString(R.string.wifi_save),
					mListener);
		} else {
			DetailedState state = mAccessPoint.getState();
			int level = mAccessPoint.getLevel();

			if (state == null && level != -1
					&& mSecurity != AccessPoint.SECURITY_EAP
					&& mSecurity != AccessPoint.SECURITY_NONE
					&& mAccessPoint.networkId == -1) {

				/**
				 * 显示新的连接界面
				 */
				if (mAccessPoint.networkId == -1) {
					mButtonNegative.setVisibility(View.GONE);
					parentLayout1.setVisibility(View.VISIBLE);
					parentLayout2.setVisibility(View.GONE);
					newPasswod = (SoftkeyboardListenEditText) findViewById(R.id.wifi_psw);
					TextView newTitle = (TextView) findViewById(R.id.wifi_title);
					newTitle.setText(mAccessPoint.ssid.toString());
					newPasswod.setImeOptions(8);
					newPasswod
							.setOnEditorActionListener(new TextView.OnEditorActionListener() {
								Toast toast = null;

								@Override
								public boolean onEditorAction(TextView v,
										int actionId, KeyEvent event) {
									Log.d("wifi", String.valueOf(actionId));
									if (actionId == 8) {
										if ((mSsid != null && mSsid.length() == 0)
												|| ((mAccessPoint == null || mAccessPoint.networkId == -1) && ((mSecurity == AccessPoint.SECURITY_WEP && newPasswod
														.length() == 0) || (mSecurity == AccessPoint.SECURITY_PSK
														&& newPasswod.length() < 8 || newPasswod
														.length() > 63)))) {

											String text;
											if (newPasswod.length() > 63) {

												text = getContext()
														.getString(
																R.string.pasw_length_to_long);
											} else {
												text = getContext()
														.getString(
																R.string.pasw_length_cue);
											}

											if (toast == null) {
												toast = MyToast.makePrompt(
														getContext(), text);
												toast.show();
											} else {
												toast.cancel();
												toast = MyToast.makePrompt(
														getContext(), text);
												toast.show();
											}

											return true;
										}
										InputMethodManager imm = (InputMethodManager) v
												.getContext()
												.getSystemService(
														Context.INPUT_METHOD_SERVICE);
										if (imm.isActive()) {
											imm.hideSoftInputFromWindow(
													v.getApplicationWindowToken(),
													0);
										}
										mListener.onClick(newPasswod);
									}

									return true;
								}
							});
					newPasswod.setDoKeyBackListener(new DoKeyBackListener() {

						@Override
						public void doKeyBack() {
							InputMethodManager inputManager = (InputMethodManager) newPasswod
									.getContext().getSystemService(
											Context.INPUT_METHOD_SERVICE);
							inputManager.hideSoftInputFromWindow(
									newPasswod.getApplicationWindowToken(), 0);
							WifiDialog.this.dismiss();
						}
					});

					openKeyBord(newPasswod);
					handler.sendEmptyMessageDelayed(0, 100);
					return;
				}
			}
			ViewGroup group = (ViewGroup) mView.findViewById(R.id.info);
			if (mView != null)
				mView.setFocusable(false);

			WifiInfo info = mAccessPoint.getInfo();

			if (mAccessPoint.networkId == -1 || edit) {
				setTitle(String.format(
						context.getString(R.string.wifi_ap_dialog_title),
						mAccessPoint.ssid));
				titleIcon.setVisibility(View.INVISIBLE);
				showSecurityFields();
			}
			if ((mAccessPoint.networkId != -1 && !edit)
					|| mSecurity == AccessPoint.SECURITY_NONE) {
				setTitle(mAccessPoint.ssid);
				titleIcon.setVisibility(View.VISIBLE);
				if (state != null) {
					addRow(group, R.string.wifi_status,
							Summary.get(getContext(), state));
				}

				String[] type = resources.getStringArray(R.array.wifi_security);
				addRow(group, R.string.wifi_security,
						type[mAccessPoint.security]);

				// if (level != -1) {
				// String[] signal = resources
				// .getStringArray(R.array.wifi_signal);
				// addRow(group, R.string.wifi_signal, signal[level]);
				// }

				if (info != null) {
					// addRow(group, R.string.wifi_speed, info.getLinkSpeed()
					// + WifiInfo.LINK_SPEED_UNITS);
					// TODO: fix the ip address for IPv6.
					int address = info.getIpAddress();
					if (address != 0) {
						addRow(group, R.string.wifi_ip_address,
								Formatter.formatIpAddress(address));
					}
					WifiManager wifiService = (WifiManager) context
							.getSystemService(Context.WIFI_SERVICE);
					int dns = wifiService.getDhcpInfo().dns1;
					if (dns != 0) {
						addRow(group, R.string.wifi_dns_address,
								Formatter.formatIpAddress(dns));
					}
				}
			}

			if (edit) {
				setButton(BUTTON_SUBMIT, context.getString(R.string.wifi_save),
						mListener);
			} else {
				if (state == null && level != -1) {

					setButton(BUTTON_SUBMIT,
							context.getString(R.string.wifi_connect), mListener);

				}
				if (mAccessPoint.networkId != -1) {
					setButton(BUTTON_FORGET,
							context.getString(R.string.wifi_forget), mListener);
				}
			}
		}
		if (mButtonPositive != null) {
			validate();
			if (mAccessPoint == null) {
				// TODO
			} else if (mPassword != null
					&& mPassword.getVisibility() == View.VISIBLE) {
				// TODO
			} else if (mButtonPositive.getVisibility() == View.VISIBLE
					&& mButtonPositive.isEnabled()) {
				mButtonPositive.requestFocus();
			} else if (mButtonNeutral.getVisibility() == View.VISIBLE) {
				mButtonNegative.requestFocus();
				// mButtonNeutral.requestFocus();
			}
		}
	}

	@Override
	public Button getButton(int whichButton) {
		switch (whichButton) {
		case BUTTON_SUBMIT:
			return mButtonPositive;
		case DialogInterface.BUTTON_NEGATIVE:
			return mButtonNegative;
		case BUTTON_FORGET:
			return mButtonNeutral;
		default:
			return null;
		}
	}

	// @Override
	public void setButton(int whichButton, CharSequence text,
			View.OnClickListener listener) {
		switch (whichButton) {
		case BUTTON_SUBMIT:
			mButtonPositive.setText(text);
			mButtonPositive.setVisibility(View.VISIBLE);
			mButtonPositive.setOnClickListener(mListener);
			break;
		case DialogInterface.BUTTON_NEGATIVE:
			mButtonNegative.setText(text);
			mButtonNegative.setVisibility(View.VISIBLE);
			mButtonNegative.setOnClickListener(mListener);
			break;
		case BUTTON_FORGET:
			mButtonNeutral.setText(text);
			mButtonNeutral.setVisibility(View.VISIBLE);
			mButtonNeutral.setOnClickListener(mListener);
			break;
		default:
			break;
		}
	}

	private void addRow(ViewGroup group, int name, String value) {
		View row = getLayoutInflater().inflate(R.layout.wifi_dialog_row, group,
				false);
		((TextView) row.findViewById(R.id.name)).setText(name);
		((TextView) row.findViewById(R.id.value)).setText(value);
		group.addView(row);
	}

	private void validate() {
		// TODO: make sure this is complete.
		if ((mSsid != null && mSsid.length() == 0)
				|| ((mAccessPoint == null || mAccessPoint.networkId == -1) && ((mSecurity == AccessPoint.SECURITY_WEP && mPassword
						.length() == 0) || (mSecurity == AccessPoint.SECURITY_PSK && mPassword
						.length() < 8)))) {
			if (mButtonNegative != null) {
				mButtonNegative.setNextFocusLeftId(R.id.button2);
				getButton(BUTTON_SUBMIT).setFocusable(false);
				getButton(BUTTON_SUBMIT).setEnabled(false);
			}

		} else {
			if (mButtonNegative != null) {
				if (mButtonNeutral.getVisibility() == View.VISIBLE) {
					mButtonNegative.setNextFocusLeftId(R.id.button3);
				} else {
					mButtonNegative.setNextFocusLeftId(R.id.button1);
				}
				getButton(BUTTON_SUBMIT).setFocusable(true);
				getButton(BUTTON_SUBMIT).setEnabled(true);
			}
		}
		if (security != null) {
			if (mSecurity == AccessPoint.SECURITY_NONE) {
				if (mSsid != null && mSsid.length() != 0) {
					security.setNextFocusDownId(0);
				} else {
					security.setNextFocusDownId(R.id.button2);
				}
			} else {
				security.setNextFocusDownId(0);
			}
		}
	}

	public void onClick(View view) {
		mPassword
				.setInputType(InputType.TYPE_CLASS_TEXT
						| (((CheckBox) view).isChecked() ? InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
								: InputType.TYPE_TEXT_VARIATION_PASSWORD));
	}

	public void onTextChanged(CharSequence s, int start, int before, int count) {
	}

	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
	}

	public void afterTextChanged(Editable editable) {
		validate();
	}

	public void onItemSelected(AdapterView parent, View view, int position,
			long id) {
		mSecurity = position;
		showSecurityFields();
		validate();
	}

	public void onSecurityChanged(int position) {
		mSecurity = position;
		showSecurityFields();
		validate();
	}

	public void onNothingSelected(AdapterView parent) {
	}

	@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
	private void showSecurityFields() {
		if (mSecurity == AccessPoint.SECURITY_NONE) {
			mView.findViewById(R.id.fields).setVisibility(View.GONE);
			return;
		}
		if (mView != null)
			mView.setFocusable(true);
		mView.findViewById(R.id.fields).setVisibility(View.VISIBLE);

		if (mPassword == null) {
			mPassword = (SoftkeyboardListenEditText) mView
					.findViewById(R.id.password);
			mPassword.addTextChangedListener(this);
			mPassword.setFocusable(true);
			mPassword.setFocusableInTouchMode(true);
			mPassword.setOnKeyListener(this);
			mPassword.setOnFocusChangeListener(new OnFocusChangeListener() {

				@Override
				public void onFocusChange(View arg0, boolean arg1) {
					if (!arg1) {
						InputMethodManager imm = (InputMethodManager) getContext()
								.getSystemService(Context.INPUT_METHOD_SERVICE);
						imm.hideSoftInputFromWindow(arg0.getWindowToken(), 0);
					}
				}
			});
			if (!isAddnet) {
				mPassword.requestFocus();
				openKeyBord(mPassword);
				handler.sendEmptyMessageDelayed(0, 100);
			}
			mCheckBox = ((CheckBox) mView.findViewById(R.id.show_password));
			mCheckBox.setOnClickListener(this);
			mCheckBox.setNextFocusDownId(R.id.button1);

			if (mAccessPoint != null && mAccessPoint.networkId != -1) {
				mPassword.setHint(R.string.wifi_unchanged);
			}
		}

		if (mSecurity != AccessPoint.SECURITY_EAP) {
			mView.findViewById(R.id.eap).setVisibility(View.GONE);
			return;
		}
		mView.findViewById(R.id.eap).setVisibility(View.VISIBLE);

		if (mEapMethod == null) {
			mEapMethod = (WheelSpinnerView) mView.findViewById(R.id.method);
			mPhase2 = (WheelSpinnerView) mView.findViewById(R.id.phase2);
			mEapCaCert = (WheelSpinnerView) mView.findViewById(R.id.ca_cert);
			mEapUserCert = (WheelSpinnerView) mView
					.findViewById(R.id.user_cert);
			mEapIdentity = (TextView) mView.findViewById(R.id.identity);
			mEapAnonymous = (TextView) mView.findViewById(R.id.anonymous);
			String[] method = getContext().getResources().getStringArray(
					R.array.wifi_eap_method);
			mEapMethod.setAdapterData(method);
			mEapMethod.setCyclic(true);
			View.OnKeyListener mEapMethodKeyListener = new View.OnKeyListener() {
				@Override
				public boolean onKey(View v, int keyCode, KeyEvent event) {
					if (event.getAction() == KeyEvent.ACTION_DOWN) {
						if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
							int position = mEapMethod.getCurrentItem() - 1;
							mEapMethod.setCurrentItem(position);
							return true;
						} else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
							int position = mEapMethod.getCurrentItem() + 1;
							mEapMethod.setCurrentItem(position);
							return true;
						}
					}
					return false;
				}
			};
			mEapMethod.setOnKeyListener(this);
			String[] phase2 = getContext().getResources().getStringArray(
					R.array.wifi_phase2_entries);
			mPhase2.setAdapterData(phase2);
			mPhase2.setCyclic(true);
			mPhase2.setOnKeyListener(this);

			loadCertificates(mEapCaCert, Credentials.CA_CERTIFICATE);
			mEapCaCert.setCyclic(true);
			mEapCaCert.setOnKeyListener(this);
			loadCertificates(mEapUserCert, Credentials.USER_PRIVATE_KEY);
			mEapUserCert.setCyclic(true);
			mEapUserCert.setOnKeyListener(this);

			if (mAccessPoint != null && mAccessPoint.networkId != -1) {
				WifiEnterpriseConfig enterpriseConfig = mAccessPoint
						.getConfig().enterpriseConfig;
				int eapMethod = enterpriseConfig.getEapMethod();
				int phase2Method = enterpriseConfig.getPhase2Method();
				mEapMethod.setCurrentItem(eapMethod);
				// showEapFieldsByMethod(eapMethod);
				switch (eapMethod) {
				case Eap.PEAP:
					switch (phase2Method) {
					case Phase2.NONE:
						mPhase2.setCurrentItem(WIFI_PEAP_PHASE2_NONE);
						break;
					case Phase2.MSCHAPV2:
						mPhase2.setCurrentItem(WIFI_PEAP_PHASE2_MSCHAPV2);
						break;
					case Phase2.GTC:
						mPhase2.setCurrentItem(WIFI_PEAP_PHASE2_GTC);
						break;
					default:
						Log.e("cedar", "Invalid phase 2 method " + phase2Method);
						break;
					}
					break;
				default:
					mPhase2.setCurrentItem(phase2Method);
					break;
				}
				setSelection(mEapCaCert,
						enterpriseConfig.getCaCertificateAlias());
				setSelection(mEapUserCert,
						enterpriseConfig.getClientCertificateAlias());
				mEapIdentity.setText(enterpriseConfig.getIdentity());
				mEapAnonymous.setText(enterpriseConfig.getAnonymousIdentity());
				// WifiConfiguration config = mAccessPoint.getConfig();
				// setSelection(mEapMethod, config.eap.value());
				// setSelection(mPhase2, config.phase2.value());
				// setCertificate(mEapCaCert, Credentials.CA_CERTIFICATE,
				// config.ca_cert.value());
				// setCertificate(mEapUserCert, Credentials.USER_PRIVATE_KEY,
				// config.private_key.value());
				// mEapIdentity.setText(config.identity.value());
				// mEapAnonymous.setText(config.anonymous_identity.value());
			}
		}
	}

	public void openKeyBord(final SoftkeyboardListenEditText view) {
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			public void run() {
				InputMethodManager inputManager = (InputMethodManager) view
						.getContext().getSystemService(
								Context.INPUT_METHOD_SERVICE);
				inputManager.showSoftInput(view, 0);
			}
		}, 200);
	}

	private void loadCertificates(WheelSpinnerView spinner, String prefix) {
		String[] certs = KeyStore.getInstance().list(prefix);
		Context context = getContext();
		String unspecified = context.getString(R.string.wifi_unspecified);

		if (certs == null || certs.length == 0) {
			certs = new String[] { unspecified };
		} else {
			String[] array = new String[certs.length + 1];
			array[0] = unspecified;
			System.arraycopy(certs, 0, array, 1, certs.length);
			certs = array;
		}
		spinner.setAdapterData(certs);
	}

	private void setCertificate(WheelSpinnerView spinner, String prefix,
			String cert) {
		prefix = KEYSTORE_SPACE + prefix;
		if (cert != null && cert.startsWith(prefix)) {
			setSelection(spinner, cert.substring(prefix.length()));
		}
	}

	private void setSelection(WheelSpinnerView spinner, String value) {
		String[] adapter = spinner.getAdapterData();
		if (value != null && adapter != null) {
			for (int i = adapter.length - 1; i >= 0; --i) {
				if (value.equals(adapter[i])) {
					spinner.setCurrentItem(i);
					break;
				}
			}
		}
	}

	View.OnClickListener mButtonHandler = new View.OnClickListener() {
		public void onClick(View v) {
			Message m = null;
			if (v == mButtonPositive && mButtonPositiveMessage != null) {
				m = Message.obtain(mButtonPositiveMessage);
			} else if (v == mButtonNegative && mButtonNegativeMessage != null) {
				m = Message.obtain(mButtonNegativeMessage);
			} else if (v == mButtonNeutral && mButtonNeutralMessage != null) {
				m = Message.obtain(mButtonNeutralMessage);
			}
			if (m != null) {
				m.sendToTarget();
			}

			// Post a message so we dismiss after the above handlers are
			// executed
			// mHandler.obtainMessage(ButtonHandler.MSG_DISMISS_DIALOG,
			// mDialogInterface).sendToTarget();
		}
	};

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		if (mPassword != null) {
			if (v.getId() == mPassword.getId()
					&& KeyEvent.ACTION_DOWN == event.getAction()
					&& keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
				handler.sendEmptyMessageDelayed(0, 150);
			}
		}

		Context context = getContext();
		if (v instanceof WheelSpinnerView) {
			if (v.getId() == R.id.security) {
				if (event.getAction() == KeyEvent.ACTION_DOWN) {
					if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
						int position = security.getCurrentItem() - 1;
						security.setCurrentItem(position);
						position = position < 0 ? type.length - 1 : position;
						onSecurityChanged(position);
						return true;
					} else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
						int position = security.getCurrentItem() + 1;
						security.setCurrentItem(position);
						position = position > type.length - 1 ? 0 : position;
						onSecurityChanged(position);
						return true;
					}
					// 　 添加这个判断，使手动添加无线无网络的焦点停在保存并连�?
					else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN
							&& security.getCurrentItem() == 0
							&& titleView.getText() == context.getResources()
									.getString(R.string.wifi_add_network)
							&& mButtonPositive.isEnabled()) {
						mButtonPositive.requestFocus();
						return true;
					}
				}
			} else {
				if (event.getAction() == KeyEvent.ACTION_DOWN) {
					if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
						int position = ((WheelSpinnerView) v).getCurrentItem() - 1;
						((WheelSpinnerView) v).setCurrentItem(position);
						return true;
					} else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
						int position = ((WheelSpinnerView) v).getCurrentItem() + 1;
						((WheelSpinnerView) v).setCurrentItem(position);
						return true;
					}
				}
			}
		}
		// TODO Auto-generated method stub
		return false;
	}

	public static void simulateKey(final int KeyCode) {

		new Thread() {
			public void run() {
				try {
					Instrumentation instrumentation = new Instrumentation();
					instrumentation.sendKeyDownUpSync(KeyCode);
				} catch (Exception e) {
					Log.d("Exception when sendKeyDownUpSync", e.toString());
				}

			}

		}.start();

	}
}
